<!--
Version 0.1
SEMF - Web Desiging Framework for Sport Event Managment
Copyright (C) 2006, SEMF Developers

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>StoreList</title>

<link href="../styles/tab.css" rel="stylesheet" type="text/css" />
<link href="../styles/foldertree.css" rel="stylesheet" type="text/css" />

<style>
.icon
{
	cursor:pointer;
}
.hor_spacer
{
	width:5px;
}
.ver_spacer
{
	height:15px;
}
</style>

<script language="javascript" src="../yui/yahoo.js"></script>
<script language="javascript" src="../yui/animation.js"></script>
<script language="javascript" src="../yui/dom.js"></script>
<script language="javascript" src="../yui/event.js"></script>
<script language="javascript" src="../yui/connection.js"></script>
<script language="javascript" src="../yui/treeview.js"></script>

<!-- SEMF utils -->
<script language="javascript" src="../bin/SEMF.js"></script>
<script language="javascript" src="../bin/util.js"></script>
<script language="javascript" src="../bin/ajax.js"></script>

<script language="javascript">

var storeTree;
var nodesArray = new Array();
var selectedId = -1;

var selectedFileFullPath = "";

var nodesMap = {};
var justCreatedDir = {};

var selectedPath = ""; // in a case selectedId is -1 or a filename

var cachedId = -1;
var copyOrMove = -1; //0 - copy, 1- move

var DIR_LIST_PREFIX = "dir_list";

var lastId = -1;

function FileNode(name, path, HTMLNode, type, filetype, parentTreeNode) 
/**
	type 	0 - file
			1 - directory
*/
{
	this.name = name;
	this.path = path;
	this.HTMLNode = HTMLNode;
	this.type = type;
	this.filetype = filetype;
	this.parentTreeNode = parentTreeNode;
	
}

function initTree()
{	
	nodesArray = new Array();
	nodesMap = {};
	justCreatedDir = {};
	cachedId = -1;
	copyOrMove = -1; //0 - copy, 1- move
	selectedId = -1;
	lastId = -1;
	
	storeTree = new YAHOO.widget.TreeView("storeList");
	//storeTree.draw();
	var parent = storeTree.getRoot();
	
	
	var data = document.getElementById("dirData");
	SEMF.util.removeWhitespace(data);
	
	//alert(SEMF.util.serialize(data.firstChild));
	
	drawTree(data.firstChild, parent, "./");
	storeTree.draw();
	
	selectAny(selectedId);
}

function drawTree(parentXML, parentTreeNode, path)
{
	var newNode = null;
	var html = null;
	var nodeId = nodesArray.length;
	
	var newPath = "";
	
	var isFile = parentXML.getAttribute("file");
	
	if (isFile == "1") { //for text node
		
		var fileName = SEMF.util.serialize(parentXML.firstChild);
		newPath = path + fileName;
		
		parentXML.setAttribute('id', 'node' + nodeId);
		
		drawFile(fileName, newPath, nodeId, parentTreeNode);
		
		if ( newPath == parent.SEMF.pageDesigner.pageInfo.selectedStoreFile)
		{
			selectfile(nodeId);
		}
	}
	else
	{
		var fileName = parentXML.getAttribute("name");
		newPath = path + fileName;
		if( parentXML.firstChild == null ) // it is an empty directory
		{
			drawEmptyDir(fileName, newPath, nodeId, parentTreeNode)
		}
		else
		{
			drawFilledDir(fileName, newPath, nodeId, parentTreeNode)
		}
		newNode = nodesArray[nodeId].HTMLNode;
		
		parentXML.setAttribute('id', 'node' + nodeId);
		
		var childs = parentXML.childNodes;
		for( var i = 0; i < childs.length; i ++)
		{
			var child = childs[i];
			drawTree(child, newNode, newPath+"/");
		}
	}
}

function selectfile(id)
{
	selectAny(id);
	var fileNode = nodesArray[id];
	//alert(fileNode.path);
	var preview = document.getElementById('storePreview');
	
	var saveOpenText = document.getElementById('saveOpenText');
	saveOpenText.value = fileNode.name;
	
	if( fileNode.filetype == "img")
	{
		preview.innerHTML = "<img src=\""+fileNode.path+"\"></img>";
		document.getElementById('filenamePreview').innerHTML = "Preview:" + fileNode.name;
		//alert(fileNode.path);
	}
	if( fileNode.filetype == "swf")
	{
		preview.innerHTML =
	    "<object classid=\"clsid:166B1BCA-3F9C-11CF-8075-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,0,0\" title=\"Test\"> "+
      "<param name=\"src\" value=\""+fileNode.path+"\" />" +
      "<embed src=\""+fileNode.path+"\" 		pluginspage=\"http://www.macromedia.com/shockwave/download/\"></embed></object>";
		document.getElementById('filenamePreview').innerHTML = "Preview:" + fileNode.name;
	}
	selectedFileFullPath = fileNode.path;
	//parent.SEMF.pageDesigner.pageInfo.selectedStoreFile = fileNode.path;
}

function selectDir(id)
{
	selectAny(id);
	//alert(id);
}

function selectAny(id)
{
	if(selectedId != -1)
	{
		var oldSelected = document.getElementById(DIR_LIST_PREFIX+selectedId);
		if(oldSelected)
		{
			oldSelected.style.fontWeight = "normal";
		}
	}
	if( id != -1)
	{
		var selected = document.getElementById(DIR_LIST_PREFIX+id);
		if(selected)
		{
			selected.style.fontWeight = "bold";
			selectedId = id;
		}
	}
}

function drawFile(fileName, newPath, nodeId, parentTreeNode)
{
	
	var imgName = "";
	var filetype = "none";
	
	if ((/^.+\.swf$/.test(fileName)))
	{
		imgName = "./images/directory/flash-file.gif";
		filetype = "swf";
	}
	else if ((/^.+\.gif$/.test(fileName)) ||
		(/^.+\.jpg$/.test(fileName))||
		(/^.+\.png$/.test(fileName))
	)
	{
		imgName = "./images/directory/photoshop-file.gif";
		filetype = "img";
	}
	else if((/^.+\.xml$/.test(fileName)))
	{
		imgName = "./images/directory/xml-file.gif";
		filetype = "semf";
	}
	else
	{
		imgName = "./images/directory/file.gif";
	}
	html = "";
	html += "<div onclick=\"selectfile("+nodeId+")\">";
	html += "<table><tr><td>";
	html += "<img src=\""+imgName+"\"></img>";
	html += "</td><td>";
	html += "<span id=\""+ DIR_LIST_PREFIX+nodeId + "\">";
	html += fileName;
	html += "</span>";
	html += "</td><tr></table>";
	html += "</div>";
	
	createNewNode(fileName, newPath, nodeId, 0, parentTreeNode, html, filetype);
	
}

//callback for the new file
atNewFile = function(fileName)
{
	var selectedNodeId = selectedId;
	
	var newPath = nodesArray[selectedId].path + "/" + fileName;
	alreadyThere = nodesMap[newPath.toLowerCase()];
	if( alreadyThere != null )
	{
		selectfile(alreadyThere);
		return;
	}
	var parentTreeNode = nodesArray[selectedNodeId].HTMLNode;
	var nodeId = nodesArray.length;
	
	var oldPath = nodesArray[selectedId].path; //selectedId is global..
	if( justCreatedDir[oldPath.toLowerCase()] )
	{
		// this should be refreshed
		fileNode = justCreatedDir[oldPath.toLowerCase()];
		oldfileName = fileNode.name;
		oldParentTreeNode = fileNode.parentTreeNode;
		storeTree.removeNode(fileNode.HTMLNode, false);
		
		drawFilledDir(oldfileName, oldPath, selectedId, oldParentTreeNode);
		
		parentTreeNode = nodesArray[selectedId].HTMLNode; // back to the new parent..
	}

	//do modify the xml..
	var dataDoc = document.getElementById("dirData");
	
	var destEle = getElementByIdWith("node" + selectedId, dataDoc.firstChild);
	if( destEle == null)
	{
		alert('Error creating new file..');
		return;
	}
	if( dataDoc.nodeType != 9 ) // avoid the mess with IE:((
	{
		dataDoc = document;
	}
	var fileNode = dataDoc.createElement("file");
	fileNode.setAttribute("id", "node" + nodeId);
	fileNode.setAttribute("name", fileName);
	fileNode.setAttribute("file", "1");
	destEle.appendChild(fileNode);
	
	drawFile(fileName, newPath, nodeId, parentTreeNode);

	storeTree.draw();
	
	//select the newly inserted tree..
	selectfile(nodeId);
}

//for new document
function createEmptyFile(isDir)
{
	if(selectedId == -1 || nodesArray[selectedId].type == 0)
	{
		alert("Select a directory to create the empty file\n");
		return;
	}
	var fileName = prompt("Name for the new File/Directory", "new file1");
	if(fileName == null)
	{
		//alert("Invalid file/directory name!!");
		return;
	}
	
	var newPath = nodesArray[selectedId].path + "/" + fileName;
	var nodeId = nodesArray.length;
	var parentTreeNode = nodesArray[selectedId].HTMLNode;
	
	
	SEMF.ajax.request("store_list_util.php",
				{
				  success: SEMF.ajax.handleSuccess,
				  failure: SEMF.ajax.handleFailure,
				  argument: {
					  fileName: fileName,
					  newPath: newPath,
					  nodeId: nodeId,
					  ps: createEmptyFileFinish,
					  parentTreeNode: parentTreeNode,
					  isDir: isDir
				  },
				  timeout: 5000,
				  params: [
				  	 'action', isDir==0?'new_file':'new_dir',
					 'newPath', newPath
				   ]
				});
}

createEmptyFileFinish = function(o)
{
	var arg = o.argument;
	var fileName = arg.fileName;
	var newPath = arg.newPath;
	var nodeId = arg.nodeId;
	var parentTreeNode = arg.parentTreeNode;
	var isDir = arg.isDir;
	
	
	var oldPath = nodesArray[selectedId].path; //selectedId is global..
	
	if( justCreatedDir[oldPath.toLowerCase()] )
	{
		// this should be refreshed
		fileNode = justCreatedDir[oldPath.toLowerCase()];
		oldfileName = fileNode.name;
		oldParentTreeNode = fileNode.parentTreeNode;
		storeTree.removeNode(fileNode.HTMLNode, false);
		
		drawFilledDir(oldfileName, oldPath, selectedId, oldParentTreeNode);
		
		parentTreeNode = nodesArray[selectedId].HTMLNode; // back to the new parent..
	}

	//do modify the xml..
	var dataDoc = document.getElementById("dirData");
	
	var destEle = getElementByIdWith("node" + selectedId, dataDoc.firstChild);
	
	
	if( destEle == null)
	{
		alert('Error creating new file..');
		return;
	}
	if( dataDoc.nodeType != 9 ) // avoid the mess with IE:((
	{
		dataDoc = document;
	}
	var fileNode = dataDoc.createElement("file");
	fileNode.setAttribute("id", "node" + nodeId);
	fileNode.setAttribute("name", fileName);
	destEle.appendChild(fileNode);
		
	if( isDir)
	{
		drawEmptyDir(fileName, newPath, nodeId, parentTreeNode);
	}
	else
	{
		fileNode.setAttribute("file", 1);
		drawFile(fileName, newPath, nodeId, parentTreeNode);
	}
	storeTree.draw();
	//select the newly inserted tree..
	selectfile(nodeId);
	//initTree();
}

function drawEmptyDir(fileName, newPath, nodeId, parentTreeNode)
{
	var imgName ="";
	var html;
	
	imgName = "./images/directory/folder-Blue.gif";
	html = "";
	html += "<div onclick=\"selectfile("+nodeId+")\">";
	html += "<table><tr><td>";
	html += "<img src=\""+imgName+"\"></img>";
	html += "</td><td>";
	html += "<span id=\""+ DIR_LIST_PREFIX+nodeId + "\">";
	html += fileName;
	html += "</span>";
	html += "</td><tr></table>";
	html += "</div>";

	
	createNewNode(fileName, newPath, nodeId, 1, parentTreeNode, html);
	
	justCreatedDir[newPath.toLowerCase()] = nodesArray[nodeId];
}

function drawFilledDir(fileName, newPath, nodeId, parentTreeNode)
{
	var html = "";
	html += "<div  onclick=\"selectDir("+nodeId+")\">";
	html += "<span id=\""+ DIR_LIST_PREFIX+nodeId + "\">";
	html += fileName;
	html += "</span>";
	html += "</div>";
	
	createNewNode(fileName, newPath, nodeId, 1, parentTreeNode, html);
}

function createNewNode(fileName, newPath, nodeId, type, parentTreeNode, html, fileType)
{
	newNode = new YAHOO.widget.HTMLNode(html,
				parentTreeNode, true, true, true);
	var fileNode = new FileNode(fileName, newPath, newNode, type, fileType, parentTreeNode);
	nodesArray[nodeId] = fileNode;
	nodesMap[newPath.toLowerCase()] = nodeId;
	
	if(lastId <= nodeId) //just to get the maximum id..
	{
		lastId = nodeId + 1;
	}
	
	return fileNode;
}

function setCopyOrMove(copyOrMoveIndex)
{
	if(selectedId == -1)
	{
		alert("Select a file to copy/move");
		return;
	}
	
	copyOrMove = copyOrMoveIndex;
	cachedId = selectedId;
}

function setPaste()
{
	if(cachedId == -1)
	{
		alert("First click on a file and click copy/move");
		return;
	}
	if(cachedId == selectedId)
	{
		alert("Select a different place to copy/move");
		return;
	}
	
	sourcefileNode = nodesArray[cachedId];
	destFileNode = nodesArray[selectedId];
	
	
	if(destFileNode.type == 0) //just a file
	{
		alert("Select a directory as the destination to paste");
		return;
	}
	
	sourcePath = sourcefileNode.path.toLowerCase();
	destPath = destFileNode.path.toLowerCase();
	
	var dataDoc = document.getElementById("dirData");
	
	var srcEle = getElementByIdWith("node" + cachedId, dataDoc.firstChild);
	var destEle = getElementByIdWith("node" + selectedId, dataDoc.firstChild);
	
	//alert(srcEle);
	//alert(destEle);
	
	if( srcEle == null || destEle == null)
	{
		alert('Error copying/moving..');
		return;
	}
	if( dataDoc.nodeType != 9 ) // avoid the mess with IE:((
	{
		dataDoc = document;
	}
	sourceClone = SEMF.util.cloneNode(dataDoc, srcEle);
	
	destEle.appendChild(sourceClone);
	
	
	if( copyOrMove == 1 ) //this is move it is reallyeasy
	{
		srcEle.parentNode.removeChild(srcEle);
	}
	
	var sourcePath = sourcefileNode.path;
	var destPath = destFileNode.path;
	
	var justDest = sourcefileNode.name;
	
	SEMF.ajax.request("store_list_util.php",
				{
				  success: SEMF.ajax.handleSuccess,
				  failure: SEMF.ajax.handleFailure,
				  argument: {
					  ps: initTree
				  },
				  timeout: 5000,
				  params: [
				  	 'action', copyOrMove==0?'copy':'move',
					 'source', sourcePath,
					 'dest', destPath,
					 'justDest', justDest
				   ]
				});
	
	//initTree();
	
	//storeTree.draw();
}


function setDelete()
{

	var dataDoc = document.getElementById("dirData");
	
	var ele = getElementByIdWith('node' + selectedId, dataDoc);
	
	if( ele != null && ele.parentNode != null)
	{
		ele.parentNode.removeChild(ele);
	}
	else
	{
		return;
	}
	
	
	var destFileNode = nodesArray[selectedId];
	var destPath = destFileNode.path;
	
	SEMF.ajax.request("store_list_util.php",
				{
				  success: SEMF.ajax.handleSuccess,
				  failure: SEMF.ajax.handleFailure,
				  argument: {
					  ps: initTree
				  },
				  timeout: 5000,
				  params: [
				  	 'action','delete',
					 'dest', destPath
				   ]
				});
}


function getElementByIdWith(id, parent)
{
	var attris = parent.attributes;
	for( i = 0; attris != null && i < attris.length ; i ++ )
	{
		var attri = attris.item(i);
		if( attri != null && attri.name == "id")
		{
			this_id = attri.value;
			if( this_id == id )
			{
				return parent;
			}
		}
	}
	if( parent.nodeType == 1 || parent.nodeType == 9)
	{
		var childs = parent.childNodes;
	
		for( var i = 0; i < childs.length; i ++)
		{
			var child = childs[i];
			
			var founded = getElementByIdWith(id, child);
			if( founded != null)
			{
				return founded;
			}
		}
	}
	return null;
} 

function closeThis()
{
	var action = "";
	var component = ""; //selected component..
	var selectedFile = "";

	var saveOpenText = document.getElementById('saveOpenText');
	selectedFile = saveOpenText.value;
	if (!(/^.+\.xml$/.test(selectedFile)))
	{
		alert("The file you open is not a component file. \nPlease select a Component to Open");
		return;
	}
		
	var destFileNode = nodesArray[selectedId];
	if(selectedFileFullPath == "")
	{
		selectedFileFullPath = destFileNode.path;
		//alert(selectedFileFullPath);
	}
	
	
	if(parent.SEMF.pageDesigner.pageInfo.openSaveFlag == 0)
	{
		action = "open";
	}
	else
	{
		action = "save";
		if(destFileNode.type == 0) //just a file
		{
			alert("Select a directory as the destination");
			return;
		}
		//should check and propmt for overwrittings..
	}
	if(parent.SEMF.pageDesigner.pageInfo.currentComponent)
	{
		component = parent.SEMF.pageDesigner.pageInfo.currentComponent.id;
	}
	SEMF.ajax.request("open_save_util.php",
				{
				  success: SEMF.ajax.handleSuccess,
				  failure: SEMF.ajax.handleFailure,
				  argument: {
					  ps: closeThisFinish,
					  file: selectedFile,
					  action: action
				  },
				  timeout: 5000,
				  params: [
				  	 'action', action,
					 'page_xml', parent.SEMF.pageDesigner.pageInfo.pageXML,
					 'component', parent.SEMF.pageDesigner.pageInfo.currentComponent.id,
					 'selected_path', selectedFileFullPath,
					 'selected_file', selectedFile
				   ]
				});
}

function closeThisFinish(o)
{
	var fileName = o.argument.file;
	if(o.argument.action == "save")
	{
		atNewFile(fileName);
	}
	else if(o.argument.action == "open")
	{	
		var selectedNodeId = selectedId;
		var fileFullPath = nodesArray[selectedId].path;
		if(nodesArray[selectedId].type != 0)
		{
			fileFullPath += "/" + fileName;
		}
		var componentName = fileName;
		var pastingHtml = 
		"<div path=\""+fileFullPath+"\" id=\"component__"+componentName+
				"\" style=\"cursor:move; \"> "+
			"<table><tr>"+
			"<td>"+
				"<img src=\"images/component/alian.png\"/>" +
				"</img>"+
			"</td>"+
			"<td style=\"font-size:12\">"+
				componentName +
			"</td>"+
			"</tr></table>"+
		"</div>";
		
		var componentSelector = parent.document.getElementById('componentSelector');
		var oldHtml = componentSelector.innerHTML;
		componentSelector.innerHTML = oldHtml + pastingHtml;
		parent.SEMF.pageDesigner.pageInfo.alianComponentCount++;
		parent.SEMF.pageDesigner.initComponents();
	}
	
	var openSavePanel = parent.SEMF.pageDesigner.pageInfo.openSavePanel;
	openSavePanel.hide();
}

</script>

</head>

<body>

<xml id="dirData" style="visiblity:none; font-size:0px">
	<?php
	include_once("util/dom.php");
	$doc = new DOMDocument('1.0', 'iso-8859-1');
	$root_ele = $doc->createElement("templates");
	$doc->appendChild($root_ele);
	$root_ele->setAttribute("name","templates");
	
	surf_dir($doc, $root_ele, "./templates/");
	
	echo serialize_node($doc->documentElement);
	
	function surf_dir($doc, $parent, $dir)
	{
		
		$d = dir($dir);
		while (false !== ($file = $d->read()))
		{	
			if (($file{0} == '.') ||
				($file{0} == '..') ||
				($file{0} == '~'))
			{
				continue;
			}
			$file_full_path = $dir.$file;
			if( is_dir($file_full_path) )
			{
				$ele = $doc-> createElement("file");
				//$ele->setAttribute("id",strtolower($file_full_path));
				$ele->setAttribute("name",$file);
				$parent->appendChild($ele);
				surf_dir($doc, $ele, $file_full_path."/");
			}
			else
			{
				
				$ele = $doc-> createElement("file");
				//$ele->setAttribute("id",strtolower($file_full_path));
				$ele->setAttribute("file","1");
				$text = $doc->createTextNode($file);
				$ele->appendChild($text);
				$parent->appendChild($ele);
			}
		}
	}
	?>
</xml>

	<div class="bottom_narrow" style="width:66%; float:left">
		<div class="left">
			<div class="right">
				<div class="top">
					<div class="bl">
						<div class="br">
							<div class="tl">
								<div class="tr_thin">
									<div id="storeList"  style="overflow:auto; width:100%; height:250px; font-size:12px";>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="bottom_narrow" style="width:33%; float:right">
		<div class="left">
			<div class="right">
				<div class="top">
					<div class="bl">
						<div class="br">
							<div class="tl">
								<div class="tr_thin">
									<div id="storePreview" style="overflow:auto; width:100%; height:220px; ">

									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div id="filenamePreview" align="center">
		Priview
	</div>
	
	<div class="ver_spacer">
	</div>

	<div style="float:left">
			<table>
			<tr>
				<td>
					<img id="saveOpenImage"
					 title="Import new file.." src="./images/store/add.png" />
				</td>
				<td>
					<input title="Filename to save/open" id="saveOpenText" type="text"></input>
				</td>
				<td style="width:155px"></td>
				<td class="hor_spacer"></td>
				<td onclick="createEmptyFile(0)" class="icon">
					<img title="Create new empty file.." src=
						"./images/store/document-txt-blue-new.png" />
				</td>
				<td onclick="createEmptyFile(1)" class="icon">
					<img title="Add new directory.." src="./images/store/folder-new.png" />
				</td>
				<td class="hor_spacer"></td>
				<td onclick="setCopyOrMove(0)" class="icon">
					<img title="Copy File.." src="./images/store/copy.png" />
				</td>
				<td onclick="setCopyOrMove(1)" class="icon">
					<img title="Cut File.." src="./images/store/cut.png" />
				</td>
				<td onclick="setPaste()" class="icon">
					<img title="Paste File.." src="./images/store/paste.png" />
				</td>
				<td  onclick="setDelete()" class="icon">
					<img title="Delete File.." src="./images/store/cancel.png" />
				</td>
				<td class="hor_spacer"></td>
				<td onclick="closeThis()" class="icon">
					<img title="OK .." src="./images/store/ok.png" />
				</td>
			</tr>
			</table>
	</div>
	<script>
		initTree();
	</script>

</body>
</html>
